package client

import (
	"context"
	"google.golang.org/grpc"
	user "watermelon/common/proto"
)

type Handler func(ctx context.Context, in user.UserClient) (interface{}, error)

func UserClient(ctx context.Context, handler Handler) (interface{}, error) {
	dial, err := grpc.Dial("127.0.0.1:8082", grpc.WithInsecure())
	if err != nil {
		return nil, err
	}
	userClient := user.NewUserClient(dial)
	res, err := handler(ctx, userClient)
	if err != nil {
		return nil, err
	}
	return res, nil
}

func SendSms(ctx context.Context, i *user.SendSmsReq) (*user.SendSmsResp, error) {
	client, err := UserClient(ctx, func(ctx context.Context, in user.UserClient) (interface{}, error) {
		sms, err := in.SendSms(ctx, i)
		if err != nil {
			return nil, err
		}
		return sms, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.SendSmsResp), nil
}

func UserLogin(ctx context.Context, i *user.UserLoginReq) (*user.UserLoginResp, error) {
	client, err := UserClient(ctx, func(ctx context.Context, in user.UserClient) (interface{}, error) {
		login, err := in.UserLogin(ctx, i)
		if err != nil {
			return nil, err
		}
		return login, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.UserLoginResp), nil
}

func UserItem(ctx context.Context, i *user.UserItemReq) (*user.UserItemResp, error) {
	client, err := UserClient(ctx, func(ctx context.Context, in user.UserClient) (interface{}, error) {
		item, err := in.UserItem(ctx, i)
		if err != nil {
			return nil, err
		}
		return item, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.UserItemResp), nil
}
func ForgetPasswrod(ctx context.Context, i *user.ForgetPasswordReq) (*user.ForgetPasswordResp, error) {
	client, err := UserClient(ctx, func(ctx context.Context, in user.UserClient) (interface{}, error) {
		password, err := in.ForgetPassword(ctx, i)
		if err != nil {
			return nil, err
		}
		return password, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.ForgetPasswordResp), nil
}

func UserCar(ctx context.Context, i *user.UserCarReq) (*user.UserCarResp, error) {
	client, err := UserClient(ctx, func(ctx context.Context, in user.UserClient) (interface{}, error) {
		car, err := in.UserCar(ctx, i)
		if err != nil {
			return nil, err
		}
		return car, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.UserCarResp), nil
}
